 //Initialize Select2 Elements
$(".select2").select2();


loadApiGroup();
$("#searchApi").on('click',function(){
	reload(1);
})



function reload(z_index){
	var limit = 10;
	var group = $("#groupId").val();
	var service = $("#serviceName").val();
	
	var start = (z_index-1)*limit;
	var param = {
		groupId : group,
		serviceName : service,
		start:start,
		limit:limit,
	}
	loading.show();
	$.ajax({
		url:'/api/getApis',
		type:'GET',
		data:param
	}).done(function(res){
		loading.hide();
		var result = res.rows;
		var pagefn = doT.template($('#tableDetail01').text());
	    $('#apiList').html(pagefn(result));
	    
	    $('.M-box').pagination({
            totalData:res.results,
            showData:10,
            coping:true,
            current:z_index,    
            prevContent:'<上一页',
            nextContent:'下一页>',
            callback:function(e){
                console.log(e.getCurrent());
                var z_index = e.getCurrent();
                reload(z_index);
            }
        },function(api){
            //console.log('error');
        });
	}).fail(function(res){
		toast.show(res.errorMsg);
	})
}

function addApi(){
	window.location = "/api/addApi";
}

function deleteApi(serviceName,version,id){
	getModal.show({content:'确定删除？',cb_l:function(){return deleteApiCb(serviceName,version,id)}});
}



function deleteApiCb(serviceName,version,id){
	var param = {
		serviceName : serviceName,
		version : version,
		id:id
	}
	$.ajax({
		url:'/api/deleteApi',
		type:'POST',
		data:param
	}).done(function(res){
		if(res.success){
			reload(1);
		}else{
			toast.show(res.errorMsg);
		}
	}).fail(function(res){
		toast.show(res.errorMsg);
	})
}

function editApi(id){
	window.location = "/api/editApi?id="+id;
}


function checkDelApiGroup(){
	var id = $("#groupId").val();
	getModal.show({content:'确定删除？',cb_l:function(){return deleteApiGroup(id)}});
}
function deleteApiGroup(id){
	var param = {
		id:id
	}
	$.ajax({
		url:'/api/deleteGroup',
		type:'POST',
		data:param
	}).done(function(res){
		if(res.success){
			toast.show("删除成功");
			loadApiGroup();
		}else{
			toast.show(res.errorMsg);
		}
	}).fail(function(res){
		toast.show(res.errorMsg);
	})
}

function addApiGroup(){
	var name=$("#groupName").val();
	
	if(name==null||name==''){
		alert("名称不能为空");
		return ;
	}
	var param = {
		name:name
	}
	$.ajax({
		url:'/api/insertGroup',
		type:'POST',
		data:param
	}).done(function(res){
		if(res.success){
			cancel('bg');
			toast.show("添加成功");
			
			loadApiGroup();
		}else{
			toast.show(res.errorMsg);
		}
	}).fail(function(res){
		toast.show(res.errorMsg);
	})
}
